<template>
  <div class="app-container">
    <!-- 任务管理 -->
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="执行器" prop="jobGroup">
        <dict-selector
          dictType="job_groups"
          :value="queryParams.jobGroup"
          @change="(val) => (queryParams.jobGroup = val)"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="任务Handler" prop="executorHandlerLike">
        <el-input
          v-model="queryParams.executorHandlerLike"
          clearable
          size="small"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="状态">
        <dict-selector
          dictType="job_trigger_status"
          :value="queryParams.triggerStatus"
          @change="(val) => (queryParams.triggerStatus = val)"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="任务描述" prop="jobDescLike">
        <el-input v-model="queryParams.jobDescLike" clearable size="small" style="width: 240px" />
      </el-form-item>
      <el-form-item label="负责人" prop="authorLike">
        <el-input v-model="queryParams.authorLike" clearable size="small" style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" :perm="['job:task:view']" />
        <reset-button @click="resetQuery" :perm="['job:task:view']" />
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <add-button @click="handleAdd" :perm="['job:task:add']" />
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </el-row>
    <el-table v-loading="loading" :data="taskList">
      <el-table-column prop="id" label="任务ID" align="center" width="120" />
      <el-table-column prop="jobDesc" label="任务描述" min-width="160" show-overflow-tooltip />
      <el-table-column
        prop="executorHandler"
        label="任务Handler"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="executorParam"
        label="默认参数"
        align="center"
        min-width="160"
        show-overflow-tooltip
      />
      <!-- <el-table-column prop="glueType" label="运行模式" align="center" width="120"></el-table-column> -->
      <el-table-column prop="jobCron" label="Cron" align="center" width="120" />
      <!-- <el-table-column prop="author" label="负责人" align="center" width="120"></el-table-column> -->
      <el-table-column prop="triggerStatus" label="任务状态" align="center" width="80">
        <template #default="scope">
          <el-popover placement="right" width="300" trigger="hover">
            <div
            >最后执行时间：
              <span class="text-muted">
                {{
                  scope.row.triggerLastTime > 0
                    ? $moment(new Date(scope.row.triggerLastTime)).format('YYYY-MM-DD HH:mm:SS')
                    : '-'
                }}
              </span>
            </div>
            <div
            >下次执行时间：
              <span class="text-success">
                {{
                  scope.row.triggerNextTime > 0
                    ? $moment(new Date(scope.row.triggerNextTime)).format('YYYY-MM-DD HH:mm:SS')
                    : '-'
                }}
              </span>
            </div>
            <template #reference>
              <span>
                <el-tag
                  v-if="scope.row.triggerStatus === 1 || scope.row.triggerStatus === '1'"
                  type="success"
                >{{ selectDictLabel(jobTriggerStatusOptions, scope.row.triggerStatus) }}
                </el-tag>
                <el-tag v-else type="danger">{{
                  selectDictLabel(jobTriggerStatusOptions, scope.row.triggerStatus)
                }}</el-tag>
              </span>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center" width="160" />
      <el-table-column label="操作" align="center" width="240px">
        <template #default="scope">
          <div class="operation">
            <text-add-button @click="handleCopy(scope.row)" text="复制" :perm="['job:task:add']" />
            <text-edit-button @click="handleUpdate(scope.row)" :perm="['job:task:edit']" />
            <text-delete-button
              @click="handleDelete(scope.row)"
              :perm="['job:task:remove']"
              :subject="scope.row.jobDesc"
            />
            <el-dropdown class="ml10" @command="(command) => handleMore(command, scope.row)">
              <span class="el-dropdown-link text-navy">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    command="start"
                    v-if="scope.row.triggerStatus === 0 || scope.row.triggerStatus === '0'"
                  >启动</el-dropdown-item
                  >
                  <el-dropdown-item
                    command="stop"
                    v-if="scope.row.triggerStatus === 1 || scope.row.triggerStatus === '1'"
                  >停止</el-dropdown-item
                  >
                  <el-dropdown-item command="trigger">执行一次</el-dropdown-item>
                  <el-dropdown-item command="group">注册节点</el-dropdown-item>
                  <el-dropdown-item command="next">执行计划</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <drag-dialog
      v-el-drag-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="open"
      width="90%"
      min-width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="执行器" prop="jobGroup">
              <dict-selector
                dictType="job_groups"
                :value="form.jobGroup"
                @change="onJobGroupChangeHandler"
                style="width: 100%"
                :clearable="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="JobHandler" prop="executorHandler">
              <el-select
                v-model="form.executorHandler"
                filterable
                placeholder="请选择"
                style="width: 100%"
                @change="doExecutorHandlerChange"
              >
                <el-option
                  v-for="item in jobHandlersOptions"
                  :key="item.value"
                  :label="item.value + '（' + item.label + '）'"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务描述" prop="jobDesc">
              <el-input v-model="form.jobDesc" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运行模式" prop="glueType">
              <dict-selector
                :dictData="jobGlueTypeOptions"
                v-model="form.glueType"
                :value="form.glueType"
                @change="(val) => (form.glueType = val)"
                style="width: 100%"
                :clearable="false"
                :defaultSelectIndex="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="路由策略" prop="executorRouteStrategy">
              <dict-selector
                :dictData="jobExecutorRouteStrategyOptions"
                v-model="form.executorRouteStrategy"
                :value="form.executorRouteStrategy"
                @change="(val) => (form.executorRouteStrategy = val)"
                style="width: 100%"
                :clearable="false"
                :defaultSelectIndex="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Cron" prop="jobCron">
              <el-popover :visible="cronPopover" width="600px" trigger="click">
                <cron-editor
                  @cron-change="changeCron"
                  @close="cronPopover = false"
                  :data="form.jobCron"
                  i18n="cn"
                />
                <template #reference>
                  <el-input
                    v-model="form.jobCron"
                    placeholder="请输入定时策略"
                    readonly
                    @click="cronPopover = true"
                  >
                    <template #append><i class="el-icon-edit"></i></template>
                  </el-input>
                </template>
              </el-popover>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="阻塞处理策略" prop="executorBlockStrategy">
              <dict-selector
                :dictData="jobExecutorBlockStrategyOptions"
                v-model="form.executorBlockStrategy"
                :value="form.executorBlockStrategy"
                @change="(val) => (form.executorBlockStrategy = val)"
                style="width: 100%"
                :clearable="false"
                :defaultSelectIndex="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="author">
              <el-input v-model="form.author" placeholder="请输入负责人名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务超时时间" prop="executorTimeout">
              <el-input v-model="form.executorTimeout" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失败重试次数" prop="executorFailRetryCount">
              <el-input v-model="form.executorFailRetryCount" placeholder="" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="子任务ID" prop="childJobId">
              <el-input v-model="form.childJobId" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警邮件" prop="alarmEmail">
              <el-input v-model="form.alarmEmail" placeholder="" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">{{
          selectedJobHandler.label + '（' + selectedJobHandler.value + '）默认参数'
        }}</el-divider>
        <span
          v-if="
            selectedJobHandler.jobHandlerParams && selectedJobHandler.jobHandlerParams.length > 0
          "
        >
          <el-row>
            <el-col
              :span="12"
              v-for="param in selectedJobHandler.jobHandlerParams"
              :key="param.value"
            >
              <el-form-item :label="param.label" :prop="param.key">
                <el-input v-model="form.inputParams[param.key]" />
                <span class="text-success">{{ param.desc }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </span>
        <span v-else>无</span>
        <JsonEditor
          v-if="form.glueType === 'BEAN' && form.executorHandler === 'dataIntegrationJsonHandler'"
          ref="jsonEditor"
          v-model="form.jsonContent"
        />
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitForm" @cancel="cancel" />
      </template>
    </drag-dialog>

    <!-- 执行一次对话框 -->
    <drag-dialog
      v-el-drag-dialog
      title="执行一次"
      :close-on-click-modal="false"
      v-model="triggerFormConfig.open"
      width="90%"
      min-width="800px"
      append-to-body
    >
      <el-form ref="form" :model="triggerForm" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务描述">{{ triggerForm.jobDesc }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="JobHandler">{{ triggerForm.executorHandler }} </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="路由策略">
              <el-tag>{{
                selectDictLabel(jobExecutorRouteStrategyOptions, triggerForm.executorRouteStrategy)
              }}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="阻塞处理策略" prop="executorBlockStrategy">
              <el-tag>{{
                selectDictLabel(jobExecutorBlockStrategyOptions, triggerForm.executorBlockStrategy)
              }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="执行器名称">{{ triggerFormConfig.executor.title }} </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="AppName">{{ triggerFormConfig.executor.appName }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-divider content-position="left">执行参数</el-divider>
            <span
              v-if="
                triggerFormConfig.jobHandler &&
                  triggerFormConfig.jobHandler.jobHandlerParams &&
                  triggerFormConfig.jobHandler.jobHandlerParams.length > 0
              "
            >
              <el-row>
                <el-col
                  :span="12"
                  v-for="param in triggerFormConfig.jobHandler.jobHandlerParams"
                  :key="param.key"
                >
                  <el-form-item :label="param.label" :prop="param.key">
                    <el-input v-model="triggerFormConfig.inputParams[param.key]" />
                    <span class="text-success">{{ param.desc }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </span>
            <span v-else>无</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-divider content-position="left">指定执行节点</el-divider>
            <span
              v-if="
                triggerFormConfig.executor.registryList &&
                  triggerFormConfig.executor.registryList.length > 0
              "
            >
              <el-row>
                <el-col :span="24">
                  <el-form-item>
                    <el-checkbox-group v-model="triggerFormConfig.selectRegistryList">
                      <el-checkbox
                        v-for="(registry, index) in triggerFormConfig.executor.registryList"
                        :key="index"
                        :label="registry"
                      />
                    </el-checkbox-group>
                    <span class="text-success"
                    >不选表示所有节点，多个节点将根据路由策略（{{
                      selectDictLabel(
                        jobExecutorRouteStrategyOptions,
                        triggerForm.executorRouteStrategy
                      )
                    }}）进行选择</span
                    >
                  </el-form-item>
                </el-col>
              </el-row>
            </span>
            <span v-else class="text-danger">无</span>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitTriggerForm" @cancel="triggerFormConfig.open = false" />
      </template>
    </drag-dialog>
  </div>
</template>

<script>
import {
  listTask,
  getExecutorRouteStrategy,
  getGlueType,
  getExecutorBlockStrategy,
  insert,
  deleteById,
  updateById,
  selectById,
  nextTriggerTime,
  start,
  stop,
  trigger
} from '@job/api/job/info'
import { selectById as selectByIdJobjson } from '@job/api/job/jobjson'
import { getExecutor, getJobHandlersByGroupId } from '@job/api/job/group'
import { debounceWrapper } from '@/utils/zmids'
import { CronEditor } from '@/components/CronEditor'
import { JsonEditor } from '@/components/JsonEditor'
import moment from "moment";

export default {
  name: 'JobInfo',
  components: { CronEditor, JsonEditor },
  data() {
    return {
      cronPopover: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格树数据
      taskList: [],
      // 弹出层标题
      title: '',
      // 任务状态列表
      jobTriggerStatusOptions: [],
      // 路由策略列表
      jobExecutorRouteStrategyOptions: [],
      // 运行模式列表
      jobGlueTypeOptions: [],
      // 阻塞处理策略列表
      jobExecutorBlockStrategyOptions: [],
      // Job Handler下拉框数据
      jobHandlersOptions: [],
      // Job Handler信息，name->对象实体
      jobHandlersMap: {},
      // 选择Job Handler
      selectedJobHandler: {},
      // 是否显示弹出层
      open: false,
      queryParams: {
        jobGroup: '',
        triggerStatus: '',
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 执行一次窗口
      triggerForm: {},
      // 执行一次窗口配置参数
      triggerFormConfig: {},
      // 表单校验
      rules: {
        jobGroup: [{ required: true, message: '执行器不能为空', trigger: 'blur' }],
        jobDesc: [{ required: true, message: '任务描述不能为空', trigger: 'blur' }],
        executorRouteStrategy: [{ required: true, message: '路由策略不能为空', trigger: 'blur' }],
        jobCron: [{ required: true, message: 'Cron不能为空', trigger: 'blur' }],
        glueType: [{ required: true, message: '运行模式不能为空', trigger: 'blur' }],
        executorHandler: [{ required: true, message: 'JobHandler不能为空', trigger: 'blur' }],
        executorBlockStrategy: [
          { required: true, message: '阻塞处理策略不能为空', trigger: 'blur' }
        ],
        author: [{ required: true, message: '负责人不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.reset()
    this.resetTriggerForm()
    this.getList()
    this.getDicts('job_trigger_status').then((response) => {
      this.jobTriggerStatusOptions = response.data
    })
    this.doGetExecutorRouteStrategy()
    this.doGetGlueType()
    this.doGetExecutorBlockStrategy()
  },
  methods: {
    changeCron(val) {
      this.form.jobCron = val
    },
    // 获取路由策略列表
    doGetExecutorRouteStrategy: debounceWrapper(function () {
      getExecutorRouteStrategy().then((response) => {
        this.jobExecutorRouteStrategyOptions = response.data
      })
    }),
    // 获取路由策略列表
    doGetGlueType: debounceWrapper(function () {
      getGlueType().then((response) => {
        this.jobGlueTypeOptions = response.data
      })
    }),
    // 获取路由策略列表
    doGetExecutorBlockStrategy: debounceWrapper(function () {
      getExecutorBlockStrategy().then((response) => {
        this.jobExecutorBlockStrategyOptions = response.data
      })
    }),
    // 查询任务管理列表
    getList: debounceWrapper(function () {
      this.loading = true
      listTask(this.queryParams).then((response) => {
        this.taskList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    }),
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 表单重置
    reset() {
      this.form = {
        jobGroup: '',
        jobDesc: '',
        executorRouteStrategy: '',
        jobCron: '',
        glueType: '',
        executorHandler: '',
        executorBlockStrategy: '',
        childJobId: '',
        executorTimeout: '',
        executorFailRetryCount: '',
        author: '',
        alarmEmail: '',
        executorParam: '',
        // 输入参数
        inputParams: {}
      }
      this.resetForm('form')
    },
    resetTriggerForm() {
      this.triggerForm = {}
      this.triggerFormConfig = {
        // 执行一次弹框是否显示
        open: false,
        // 执行一次Job Handler
        jobHandler: {},
        // 执行一次：执行器信息
        executor: [],
        // 执行一次：指定的运行节点
        selectRegistryList: [],
        // 输入参数
        inputParams: {}
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加调度任务'
    },
    /** 复制按钮操作 */
    handleCopy: debounceWrapper(function (row) {
      this.loading = true
      this.reset()
      selectById(row.id).then((response) => {
        this.loading = false
        this.form = response.data
        // 复制操作，删除ID
        this.form.id = undefined
        // 获取配置参数
        if (this.form.executorParam) {
          const inputParams = JSON.parse(this.form.executorParam)
          this.form.inputParams = inputParams
          // this.$set(this.form, "inputParams", inputParams);
        } else {
          this.form.inputParams = {}
          // this.$set(this.form, "inputParams", {});
        }
        this.open = true
        this.title = '复制新增任务信息'
      })
    }),
    /** 修改按钮操作 */
    handleUpdate: debounceWrapper(function (row) {
      this.loading = true
      this.reset()
      selectById(row.id).then(async (response) => {
        this.loading = false
        this.form = response.data
        // 获取配置参数
        if (this.form.executorParam) {
          const inputParams = JSON.parse(this.form.executorParam)
          this.form.inputParams = inputParams
          // this.$set(this.form, "inputParams", inputParams);
        } else {
          this.form.inputParams = {}
          // this.$set(this.form, "inputParams", {});
        }

        //根据jsonJobId 获取 jsonContent
        if (JSON.parse(response.data.executorParam).jsonJobId) {
          await selectByIdJobjson(JSON.parse(response.data.executorParam).jsonJobId).then(
            (response) => {
              this.form.jsonContent = JSON.parse(response.data.jsonContent)
            }
          )
        }

        this.open = true
        this.title = '修改任务信息'
      })
    }),
    /** 删除按钮操作 */
    handleDelete: debounceWrapper(function (row) {
      this.loading = true
      deleteById(row.id)
        .then(() => {
          this.loading = false
          this.msgSuccess('删除成功')
          this.getList()
        })
        .catch((e) => {
          this.loading = false
          this.msgError('删除失败')
          console.error(e)
        })
    }),
    /** 提交按钮 */
    submitForm: debounceWrapper(function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          // 构造默认参数
          this.form.executorParam = JSON.stringify(this.form.inputParams || {})

          if (this.form.id != undefined) {
            updateById(this.form).then((response) => {
              this.loading = false
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            insert(this.form).then((response) => {
              this.loading = false
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    }),
    // 更多按钮操作
    handleMore: debounceWrapper(function (command, row) {
      if ('start' === command) {
        this.doStart(row)
      } else if ('stop' === command) {
        this.doStop(row)
      } else if ('trigger' === command) {
        this.showTrigger(row)
      } else if ('log' === command) {
        this.showRunLog(row)
      } else if ('group' === command) {
        this.showGroup(row)
      } else if ('next' === command) {
        this.showNextTriggerTime(row)
      }
    }),
    // 显示运行日志
    showRunLog: debounceWrapper(function (row) {}),
    // 显示注册节点
    showGroup: debounceWrapper(function (row) {
      this.loading = true
      getExecutor(row.jobGroup).then((response) => {
        this.loading = false
        if (response.data && response.data.registryList) {
          this.$alert(response.data.registryList, '注册节点信息', {
            confirmButtonText: '关闭'
          })
        } else {
          this.$alert('无', '注册节点信息', {
            confirmButtonText: '关闭'
          })
        }
      })
    }),
    // 显示执行计划
    showNextTriggerTime: debounceWrapper(function (row) {
      this.loading = true
      nextTriggerTime(row.jobCron).then((response) => {
        this.loading = false
        if (response.data && response.data.length && response.data.length > 0) {
          var html = '<ul>'
          response.data.forEach((d) => {
            html = html + '<li>' + d + '</li>'
          })
          html = html + '</ul>'

          this.$alert(html, '执行计划(最近5次)', {
            confirmButtonText: '关闭',
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$alert('无', '执行计划(最近5次)', {
            confirmButtonText: '关闭'
          })
        }
      })
    }),
    // 触发一次
    showTrigger(row) {
      this.loading = true
      this.resetTriggerForm()
      selectById(row.id).then((response) => {
        this.triggerForm = response.data
        // 设置配置参数
        if (this.triggerForm.executorParam) {
          const inputParams = JSON.parse(this.triggerForm.executorParam)
          this.triggerFormConfig.inputParams = inputParams
          // this.$set(this.triggerFormConfig, "inputParams", inputParams);
        } else {
          this.triggerFormConfig.inputParams = {}
          // this.$set(this.triggerFormConfig, "inputParams", {});
        }
        // 获取执行器Hander信息
        this.doGetJobHandlersByGroupId(this.triggerForm.jobGroup, () => {
          this.loading = false
          this.triggerFormConfig.jobHandler = this.jobHandlersMap[this.triggerForm.executorHandler]
          if (this.triggerFormConfig.jobHandler === undefined) {
            this.msgError(
              '执行器ID[' +
                this.triggerForm.jobGroup +
                ']中不存在任务[' +
                this.triggerForm.executorHandler +
                ']'
            )
          } else {
            this.triggerFormConfig.open = true
            console.log('this.triggerForm', this.triggerForm)
            console.log('this.triggerFormConfig', this.triggerFormConfig)

            // 获取执行器节点列表
            getExecutor(this.triggerForm.jobGroup).then((response) => {
              if (response.data) {
                this.triggerFormConfig.executor = response.data
                if (
                  this.triggerFormConfig.executor &&
                  this.triggerFormConfig.executor.registryList
                ) {
                  this.triggerFormConfig.selectRegistryList =
                    this.triggerFormConfig.executor.registryList
                }
              }
            })
          }
        })
      })
    },
    /** 提交按钮 */
    submitTriggerForm: debounceWrapper(function () {
      if (
        this.triggerFormConfig.executor.registryList &&
        this.triggerFormConfig.executor.registryList.length > 0
      ) {
        this.loading = true
        const param = {
          id: this.triggerForm.id,
          executorParam: JSON.stringify(this.triggerFormConfig.inputParams),
          addressList: this.triggerFormConfig.selectRegistryList.join(',')
        }
        trigger(param).then((response) => {
          this.loading = false
          this.msgSuccess('启动成功')
          this.resetTriggerForm()
        })
      } else {
        this.msgError('执行器注册节点不存在，无法执行')
      }
    }),
    // 启动
    doStart: debounceWrapper(function (row) {
      this.loading = true
      start(row.id).then((response) => {
        this.loading = false
        this.msgSuccess('启动成功')
        this.getList()
      })
    }),
    // 停止
    doStop: debounceWrapper(function (row) {
      this.loading = true
      stop(row.id).then((response) => {
        this.loading = false
        this.msgSuccess('停止成功')
        this.getList()
      })
    }),
    // 执行器下拉框change事件
    onJobGroupChangeHandler(val) {
      this.form.jobGroup = val
      this.doGetJobHandlersByGroupId(this.form && this.form.jobGroup, () => {
        if (this.jobHandlersOptions && this.jobHandlersOptions.length <= 0) {
          this.msgError('该执行器下不存在任何JobHandler')
        } else {
          // 如果是新增则默认第一个
          if (this.form.id === undefined) {
            this.form.executorHandler = this.jobHandlersOptions[0].value
          } else {
            if (this.jobHandlersMap[this.form.executorHandler] === undefined) {
              this.msgError('该执行器下不存在[' + this.form.executorHandler + ']')
            } else {
              this.doExecutorHandlerChange(this.form.executorHandler)
            }
          }
        }
      })
    },
    // 获取执行器的Job Handler列表
    doGetJobHandlersByGroupId(jobGroup, callback) {
      this.jobHandlersOptions = []
      this.jobHandlersMap = {}
      if (jobGroup) {
        getJobHandlersByGroupId(jobGroup).then((response) => {
          this.jobHandlersOptions = response.data || []
          if (this.jobHandlersOptions.length > 0) {
            this.jobHandlersOptions.forEach((e) => {
              this.jobHandlersMap[e.value] = e
            })
          }
          if (typeof callback === 'function') {
            callback()
          }
        })
      }
    },
    // 选择执行器Handler之后
    doExecutorHandlerChange(val) {
      this.selectedJobHandler = this.jobHandlersMap[val]
      // 不是新增才获取
      if (this.form.id === undefined) {
        // if (!this.form.jobDesc) {
        this.form.jobDesc =
          this.selectedJobHandler.label + '（' + this.selectedJobHandler.value + '）'
        // }
        this.form.inputParams = {}
        // 设置Handler参数
        if (
          this.selectedJobHandler.jobHandlerParams &&
          this.selectedJobHandler.jobHandlerParams.length > 0
        ) {
          this.selectedJobHandler.jobHandlerParams.forEach((p) => {
            this.form.inputParams[p.key] = p.dftValue
            // this.$set(this.form.inputParams, p.key, p.dftValue);
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.operation {
  display: flex;
  align-items: center;
  font-size: 12px;

  .el-dropdown-link {
    font-size: 12px;
  }
}
</style>
